<?php


namespace app\api\controller;


use app\service\model\ActivityModel;
use app\service\model\AttributeModel;
use app\service\model\GoodsActivityMemberModel;
use app\service\model\GoodsActivityModel;
use app\service\model\GoodsModel;
use app\service\Token;
use app\service\Y;

class Goods extends BaseApi
{

    /**
     * 商品列表
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function goods_list(): \think\response\Json
    {
        $where[] = ['status', '=', 1];

        $category_id = input('param.category_id', 0);
        if ($category_id) {
            $where[] = ['category_id', '=', $category_id];
        }

        $goods = GoodsModel::with('images')->where($where)->paginate();
        return Y::success($goods, '商品列表');
    }

    /**
     * 商品详情
     * @return \think\response\Json
     * @throws \app\service\exception\ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function goods_info(): \think\response\Json
    {
        $id = input('param.id', 0);
        if (!$id) {
            return Y::error('参数错误');
        }

        $where = [
            ['id', '=', $id],
            ['status', '=', 1]
        ];

        $goods = GoodsModel::with(['images', 'content', 'sku'])->where($where)->find();
        if (!$goods) {
            return Y::error('商品不存在');
        }

        $goods['attribute'] = AttributeModel::select();

        // 获取商品最优惠的活动
        $goods['activity'] = GoodsActivityModel::getActivity($id);

        return Y::success($goods, '商品信息');
    }

}